#! env python

from argparse import ArgumentParser
import os, shutil, pathlib, zipfile

keep_dir: bool = False
package_name: str = ''
prog_suffix: str = ''
lib_suffix: str = ''

if os.name == 'posix':
    prog_suffix = ''
    lib_suffix = '.so'
elif os.name == 'nt':
    prog_suffix = '.exe'
    lib_suffix = '.dll'
else:
    raise RuntimeError('pack_release don\'t support current platform')

files_to_copy: list[str] = [
    'build/signalBox' + prog_suffix,
    'readme.md',
    'readme_en.md',
    'coefficient_demo',
    'workspace_demo',
]

# parse cli args
def parse_arg() -> None:
    global keep_dir, package_name
    parser = ArgumentParser('pack_release')
    parser.add_argument('--keep-dir', '-k', dest='keep_dir', action='store_true', default=False)
    parser.add_argument('version', type=str)

    parse_res = parser.parse_args()
    keep_dir = parse_res.keep_dir
    package_name = 'signal-test-box-v' + parse_res.version

def create_release() -> None:
    lib_path = os.path.join(package_name, 'lib')

    if not os.path.exists(package_name):
        os.makedirs(lib_path)

    # copy all files & dirs we need
    for entry in files_to_copy:
        if os.path.isdir(entry):
            shutil.copytree(entry, os.path.join(package_name, entry))
        else:
            shutil.copy(entry, package_name)

    # copy all lib files
    lib_build_path = pathlib.Path(os.path.join('build', 'lib'))
    lib_files = lib_build_path.glob('*' + lib_suffix)

    for lib_file in lib_files:
        shutil.copy(lib_file, lib_path)

    # copy readme for libs
    shutil.copy(os.path.join('lib', 'readme.md'), lib_path)

    # execute windeployqt
    os.system('windeployqt ' + os.path.join(package_name, 'signalBox' + prog_suffix))

    # zip compression
    zip_file = zipfile.ZipFile(package_name + '.zip', 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9)
    for dirpath, _, filenames in os.walk(package_name):
        for file in filenames:
            fn = os.path.join(dirpath, file)
            print('Adding:', fn)
            zip_file.write(fn)

    if keep_dir == False:
        shutil.rmtree(package_name, ignore_errors=True)
        

if __name__ == '__main__':
    parse_arg()
    create_release()
